#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <time.h>

#define DEVICE_PATH "/dev/dma_mmap"
#define BUFFER_SIZE (3 * 4096) // 3页大小

int main()
{
	int fd;
	char *map;
	int i;

	fd = open(DEVICE_PATH, O_RDWR);
	if (fd < 0) {
		perror("Failed to open device");
		return 1;
	}

	map = mmap(NULL, BUFFER_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd,
		   0);
	if (map == MAP_FAILED) {
		perror("Failed to mmap");
		close(fd);
		return 1;
	}

	printf("Before bytes: ");
	for (i = 0; i < 10; i++) {
		printf("%02x ", (unsigned char)map[BUFFER_SIZE - 1 - i]);
	}
	printf("\n");

	// 生成随机数据并写入
	srand(time(NULL));
	for (i = 0; i < BUFFER_SIZE; i++) {
		map[i] = rand() % 256;
	}
	printf("Written random data to mapped memory\n");

	// 验证前10个字节
	printf("First 10 bytes: ");
	for (i = 0; i < 10; i++) {
		printf("%02x ", (unsigned char)map[BUFFER_SIZE - 1 - i]);
	}

	memcpy(map + BUFFER_SIZE - 20, "test_data ==============", 10);

	map[BUFFER_SIZE - 10] = '\0';
	printf("get map %s\n", &map[BUFFER_SIZE - 20]);
	printf("\n");

	// 读取并计算校验和
	unsigned long sum = 0;
	for (i = 0; i < BUFFER_SIZE; i++) {
		sum += map[BUFFER_SIZE - 1 - i];
	}
	printf("Checksum: 0x%lx\n", sum);

	munmap(map, BUFFER_SIZE);
	close(fd);
	return 0;
}